package com.quad.innovators.salesease.aspect;

import com.quad.innovators.salesease.annotation.FunctionPermission;
import com.quad.innovators.salesease.enums.ResultCode;
import com.quad.innovators.salesease.exception.BusinessException;
import com.quad.innovators.salesease.security.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 处理功能权限的切面
 *
 */
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class FunctionPermissionAspect {

    private final PermissionService permissionService;


    /**
     * 防重复提交切点
     */
    @Pointcut("@annotation(functionPermission)")
    public void preventFunctionPermissionPointCut(FunctionPermission functionPermission) {
        log.info("定义防重复提交切点");
    }

    @Around("preventFunctionPermissionPointCut(functionPermission)")
    public Object doAround(ProceedingJoinPoint pjp, FunctionPermission functionPermission) throws Throwable {
        String permissionCode = functionPermission.permissionCode();
        boolean hasPerm = permissionService.hasPerm(permissionCode);
        if(!hasPerm) {
            throw  BusinessException.resultCode(ResultCode.FORBID); // 抛出重复提交提示信息
        }
        return pjp.proceed();
    }
}
